﻿namespace Amazon.Checkout.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using Helpers;

    public class ShippingRecord
    {
        [Required]
        public virtual int Id { get; set; }

        public virtual string IncludedRegionsString { get; set; }

        public virtual string ExcludedRegionsString { get; set; }

        public virtual decimal ShipmentBasedShippingRate { get; set; }

        public virtual decimal WeightBasedShippingRate { get; set; }

        public virtual decimal ItemQuantityBasedShippingRate { get; set; }

        public virtual string ShipmentRateType { get; set; }

        public virtual bool PoBoxSupported { get; set; }

        public virtual string DisplayableShippingLabel { get; set; }

        public virtual int ServiceLevel { get; set; }

        public virtual AmazonCheckout.ServiceLevel GetServiceLevel()
        {
            return (AmazonCheckout.ServiceLevel)this.ServiceLevel;
        }

        public virtual void SetServiceLevel(AmazonCheckout.ServiceLevel value)
        {
            this.ServiceLevel = (int)value;
        }

        public virtual IEnumerable<AmazonCheckout.Region> GetIncludedRegions()
        {
            return GetRegionsFromString(this.IncludedRegionsString);
        }

        public virtual IEnumerable<AmazonCheckout.Region> GetExcludedRegions()
        {
            return GetRegionsFromString(this.ExcludedRegionsString);
        }

        private static IEnumerable<AmazonCheckout.Region> GetRegionsFromString(string regionString)
        {
            if (string.IsNullOrEmpty(regionString))
            {
                return new List<AmazonCheckout.Region>();
            }

            return regionString.Split(',').Select(GetRegionFromString).Where(r => r != null);
        }

        private static AmazonCheckout.Region GetRegionFromString(string regionString)
        {
            if (!regionString.Contains("|"))
            {
                return null;
            }

            var split = regionString.Split('|');

            var regionType = split[0];
            var regionData = split[1];

            var region = AmazonCheckout.Region.Create(regionType, regionData);
            return region;
        }
    }
}